/*
 *	               _ooOoo_ 
 *	              o8888888o 
 *	              88" . "88 
 *	              (| -_- |) 
 *	              O\  =  /O 
 *	           ____/`---'\____ 
 *	         .'  \\|     |//  `. 
 *	        /  \\|||  :  |||//  \ 
 *	       /  _||||| -:- |||||-  \ 
 *	       |   | \\\  -  /// |   | 
 * 	       | \_|  ''\---/''  |   | 
 * 	       \  .-\__  `-`  ___/-. / 
 * 	    ___ `. .'  /--.--\  `. . __ 
 *	  ."" '<  `.___\_<|>_/___.'  >'"". 
 *	 | | :  `- \`.;`\ _ /`;.`/ - ` : | | 
 *	 \  \ `-.   \_ __\ /__ _/   .-` /  / 
 *======`-.____`-.___\_____/___.-`____.-'====== 
 *                   `=---=' 
 *^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 
 *佛祖保佑       永无BUG 
 * File name:          FileUtil.java
 * Copyright@blog.ilvelh.com(China)
 * Editor:           JDK1.7_40
 */
package com.ilvelh.tools;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;

/**
 * 文件读取和写入操作
 * <p>
 * Author: ilvelh
 * <p>
 * Date:2014-9-10 Time:下午5:27:03
 * <p>
 */
public class FileUtil {
	/**
	 * 从文件中读取字符串
	 * 
	 * @param file
	 * @return
	 */
	public static String read(File file) {
		try {
			FileInputStream f = new FileInputStream(file);
			BufferedReader dr = new BufferedReader(new InputStreamReader(f));
			StringBuffer sb = new StringBuffer();
			String line = null;
			while ((line = dr.readLine()) != null) {
				sb.append(line);
			}
			return sb.toString();
		} catch (Exception e) {
			System.out.println("读取文件失败," + e.getMessage());
		}
		return null;
	}

	/**
	 * 将字符串写入到文件
	 * 
	 * @param file
	 * @param coneten
	 * @param isappend
	 *            是否要追加内容
	 * @return 返回是否写入成功
	 */
	public static boolean write(File file, String coneten, boolean isappend) {
		if (file == null) {
			System.out.println("要写入的文件不存在");
			return false;
		}
		try {
			if (file.exists()) {
				file.createNewFile();
			}
			FileWriter fw = new FileWriter(file, isappend);
			fw.write(coneten);
			fw.flush();
			fw.close();
			return true;
		} catch (Exception e) {
			System.out.println("写入文件失败," + e.getMessage());
		}
		return false;
	}
}
